import React, { useState, useEffect, useMemo } from 'react'
import { Card, Form, Input, InputNumber } from 'antd'
import { dragBus, propUpdateBus } from '../utils/dragBus'
import type { BodyItem } from '../types'

// 定义表单字段配置类型
interface FormFieldConfig {
  name: string | string[]
  label: string
  component: React.ReactNode
  hidden?: boolean
}

export const Prop = () => {
  const [form] = Form.useForm()
  const [currentComponent, setCurrentComponent] = useState<BodyItem | null>(null)

  // 定义不同组件类型的表单字段配置
  const formFieldsConfig = useMemo(() => {
    if (!currentComponent) return []

    const baseFields: FormFieldConfig[] = [
      {
        name: 'type',
        label: '组件类型',
        component: <Input disabled />
      }
    ]

    const typeSpecificFields: Record<string, FormFieldConfig[]> = {
      notice: [
        {
          name: 'title',
          label: '标题',
          component: <Input />
        },
        {
          name: 'content',
          label: '内容',
          component: <Input.TextArea />
        }
      ],
      search: [
        {
          name: 'placeholder',
          label: '占位符',
          component: <Input />
        },
        {
          name: 'height',
          label: '高度',
          component: <InputNumber style={{ width: '100%' }} />
        },
        {
          name: 'margin',
          label: '外边距',
          component: <Input />
        },
        {
          name: 'backgroundColor',
          label: '背景颜色',
          component: <Input />
        }
      ]
    }

    return [
      ...baseFields,
      ...(typeSpecificFields[currentComponent.type] || [])
    ]
  }, [currentComponent])

  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      // 检查点击事件是否来自设计器中的组件
      const target = e.target as HTMLElement
      const designerElement = target.closest('#phone-inner [data-index]')
      
      if (designerElement && dragBus.payload) {
        // 点击的是设计器中的组件
        const componentData = dragBus.payload as BodyItem
        setCurrentComponent(componentData)
        form.setFieldsValue(componentData)
      } else if (!target.closest('.ant-card')) {
        // 点击的是其他区域，清空选中组件
        setCurrentComponent(null)
        form.resetFields()
      }
    }

    document.addEventListener('click', handleClick)
    return () => {
      document.removeEventListener('click', handleClick)
    }
  }, [form])

  const handleValuesChange = (changedValues: Record<string, unknown>) => {
    if (currentComponent) {
      const updatedComponent = { ...currentComponent, ...changedValues }
      setCurrentComponent(updatedComponent)
      
      // 将更新发送到设计器
      if (currentComponent._index !== undefined) {
        propUpdateBus.emit({
          index: currentComponent._index,
          data: changedValues
        })
      }
      
      console.log('Component updated:', updatedComponent)
    }
  }

  // 渲染表单字段
  const renderFormFields = () => {
    return formFieldsConfig.map((field) => (
      <Form.Item
        key={Array.isArray(field.name) ? field.name.join('-') : field.name}
        label={field.label}
        name={field.name}
        hidden={field.hidden}
      >
        {field.component}
      </Form.Item>
    ))
  }

  return (
    <Card title="属性配置" style={{ width: 300, margin: 12 }}>
      {currentComponent ? (
        <Form
          form={form}
          onValuesChange={handleValuesChange}
          layout="vertical"
        >
          {renderFormFields()}
        </Form>
      ) : (
        <div>请选择一个组件以编辑其属性</div>
      )}
    </Card>
  )
}